package com.dxg.msns.upload.controller;

import com.dxg.msns.auth.entity.UserInfo;
import com.dxg.msns.auth.utils.CookieUtils;
import com.dxg.msns.auth.utils.JwtUtils;
import com.dxg.msns.common.util.Result;
import com.dxg.msns.music.pojo.Music;
import com.dxg.msns.upload.service.UploadService;
import com.dxg.msns.upload.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/api/upload")
@Slf4j
public class UploadController {

    @Autowired
    private UploadService uploadService;
    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("image")
    public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile[] file, HttpServletRequest request,
            HttpServletResponse response) {
        String url = this.uploadService.upload(file);
        if (StringUtils.isBlank(url)) {
            return ResponseEntity.badRequest().build();
        }
        // CookieUtils.setCookie(request,response,"MSNS_TOKEN",token,30,null,true);
        return ResponseEntity.ok(url);
    }

    @PostMapping("music")
    public ResponseEntity<Music> uploadMusic(@RequestParam("file") MultipartFile file, HttpServletRequest request,
            HttpServletResponse response) {
        Music music = this.uploadService.uploadMusic(file);
        if (music == null) {
            return ResponseEntity.badRequest().build();
        }
        // CookieUtils.setCookie(request,response,"MSNS_TOKEN",token,30,null,true);

        return ResponseEntity.ok(music);
    }

    @PostMapping
    public Result<String> upload(MultipartFile file) {
        log.info("文件上传:{}", file);

        try {
            String originalFilename = file.getOriginalFilename();
            // 截取扩展名
            String extention = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = UUID.randomUUID().toString() + extention;

            // 文件的请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败:{}", e);
        }

        return Result.error("文件上传失败");
    }

    @PostMapping("/test")
    private String test() {
        System.out.println("welcome!");
        return "welcome!";
    }
}
